<template>
	<view class="p-3">
		<coupon v-for="(item,index) in list" :key="index" :item="item" :index="index" @tap="getCoupon(item)">
			<text v-if="!item.status">已失效</text>
			<text v-else-if="item.disabled">已领取</text>
			<text v-else>马上领取</text>
		</coupon>
		<view v-if="list.length > 0" class="d-flex a-center j-center py-3"><text class="font-md text-light-muted">{{item.loadtext}}</text>
		</view>
		<no-thing v-else msg="没有优惠券"></no-thing>
	</view>
</template>

<script>
	import coupon from "../../components/order-coupon/coupon.vue";
	import noThing from '@/components/common/no-thing.vue';
	export default {
		components: {
			coupon,
			noThing
		},
		data() {
			return {
				page: 1,
				list: [],
				loadtext:"上拉加载更多"
			}
		},
		onLoad() {
			this.getData()
		},
		onPullDownRefresh() {
			this.page = 1
			this.getData().then(res => {
				uni.stopPullDownRefresh()
			}).catch(err => {
				uni.stopPullDownRefresh()
			})
		},
		onReachBottom() {
			if(this.loadtext !=='上拉加载更多'){
				return;
			}
			this.loadtext = '加载中...';
			this.page++;
			this.getData()
			
		},
		methods: {
			getData() {
				return new Promise((res, rej) => {
					this.$H.get('/coupon/' + this.page, {}, {
						token: true
					}).then(result => {
						this.list = result.map(item => {
							let time = (new Date()).getTime()
							let status = (item.end_time > time / 1000) && item.status
							return {
								id: item.id,
								title: item.name,
								start_time: item.start_time,
								end_time: item.end_time,
								price: item.value,
								desc: item.desc,
								status,
								disabled: false
							}
						})
						this.loadtext = (result.length === 5) ? '上拉加载更多' : '没有更多了'
						res(res)
					}).catch(err => {
						this.page--;
						rej(err)
					})
				})
			},
			getCoupon(item) {
				if(!item.status){
					uni.showToast({
						title: '优惠券已失效',
						icon: 'none'
					});
				}else if(item.disabled){
					uni.showToast({
						title: '已经领取过了',
						icon: 'none'
					});
				}else{
					this.$H.post('/getcoupon/' + item.id, {}, {
						token: true
					}).then(res => {
						item.disabled = true
						uni.showToast({
							title: '领取成功',
							icon: 'none'
						});
					})
				}
			}
		}
	}
</script>

<style>

</style>